package com.bsuir.avareader;

import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import com.bsuir.avareader.adapters.FileAdapter;
import com.bsuir.avareader.logic.FileManager;

public class OpenFileActivity extends ListActivity {
	List<String> items = new ArrayList<String>();
	public static FileManager fileManager = new FileManager();
	FileAdapter fileAdapter;
	private ImageView imageBack;
	static final int DIALOG_ID = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.open_file);
		 if (!FileManager.isSDCardMounted()) {
			 showDialog(DIALOG_ID);
		 }
		imageBack = (ImageView) findViewById(R.id.imageView);
		fileAdapter = new FileAdapter(this);
		setListAdapter(fileAdapter);
		items = fileManager.getDir();
		fileAdapter.setItems(items);
		imageBack.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				fileManager.upOneLevel();
				fileAdapter.setItems(items);
			}
		});
	}

	@Override
	public void onBackPressed() {
		items = fileManager.upOneLevel();
		if (items != null) {
			fileAdapter.setItems(items);
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id) {

		if (fileManager.itemIsDirectory(items.get(position))) {
			fileManager.setCurrentDirectory(items.get(position));
			items = fileManager.getDir();
			fileAdapter.setItems(items);
		} else {
			Intent intent = new Intent();
			intent.putExtra("file", (fileManager.getFile(items.get(position))).getAbsolutePath());
			setResult(RESULT_OK, intent);
			finish();
		}
	}
	
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DIALOG_ID:			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.sdcard_dont_mounted);
			builder.setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					System.exit(0);
								
				}
			});			
			builder.setCancelable(false);
			dialog = builder.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}
}
